package com.wing.supplier.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.wing.auth.service.AuthService;
import com.wing.common.utils.JsonResult;
import com.wing.redis.utils.redis.RedisHelperImpl;
import com.wing.set.entity.ChanjetSet;
import com.wing.set.service.ChanjetSetService;
import com.wing.supplier.entity.request.PartnerTypeCreateRequest;
import com.wing.supplier.entity.request.SupplierCreateRequest;
import com.wing.supplier.entity.request.SupplierPartnerClassCreateRequest;
import com.wing.supplier.entity.response.SupplierPartnerClassResponse;
import com.wing.supplier.entity.response.SupplierPartnerCodeClassResponse;
import com.wing.supplier.entity.response.SupplierQueryResponse;
import com.wing.util.ConstantsUtil;
import com.wing.util.HttpsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 仓库管理
 */
@Service
@Slf4j
public class SupplierServiceImpl implements SupplierService {

    @Resource
    RedisHelperImpl redisHelper;

    @Resource
    AuthService authService;

    @Resource
    ChanjetSetService chanjetSetService;

    @Override
    public List<SupplierQueryResponse> getSupplierList() {
        List<SupplierQueryResponse> supplierQueryResponses=new ArrayList<>();
        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
        headers.put("openToken", redisHelper.getValue("chanjetToken").toString());

        Map<String, Object> param = new HashMap<>();
        HashMap resultMap= new HashMap<>();
        resultMap.put("SelectFields","ID,Code,Name,PartnerAddresDTOs.Contact,PartnerAddresDTOs.MobilePhone,MadeRecordDate,PartnerType.Name");
        param.put("param", resultMap);

     /*   HashMap resultMap2= new HashMap<>();
        resultMap2.put("Name", "供应商");
        param.put("PartnerType", resultMap2);
*/
        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.QUERY_SUPPLIER, headers, JSON.toJSONString(param));

        // 将字符串解析为JSONArray
        JSONArray objects = JSON.parseArray(result);
        for (int i = 0; i < objects.size(); i++) {
            JSONObject jsonObject = objects.getJSONObject(i);

            SupplierQueryResponse supplierQueryResponse=new SupplierQueryResponse();


            // 设置直接属性
            supplierQueryResponse.setCode(jsonObject.getString("Code"));
            supplierQueryResponse.setName(jsonObject.getString("Name"));
            supplierQueryResponse.setID(jsonObject.getString("ID"));

            JSONObject partnerType = jsonObject.getJSONObject("PartnerType");
            String partnerTypeName = partnerType.getString("Name");
            supplierQueryResponse.setPartnerTypeName(partnerTypeName);
            supplierQueryResponses.add(supplierQueryResponse);
        }


        return supplierQueryResponses;
    }

    @Override
    public JsonResult createSupplier(SupplierCreateRequest supplierCreateRequest) {
        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
        headers.put("openToken", redisHelper.getValue("chanjetToken").toString());

        Map<String, Object> param = new HashMap<>();
        Map<String, Object> deptParamObj = new HashMap<>();

        deptParamObj.put("Code", supplierCreateRequest.getCode());
        deptParamObj.put("Name", supplierCreateRequest.getName());

        PartnerTypeCreateRequest partnerType = supplierCreateRequest.getPartnerType();
        deptParamObj.put("PartnerType", partnerType);
        deptParamObj.put("PartnerClass", supplierCreateRequest.getPartnerClass());
        param.put("dto", deptParamObj);

        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.CREATE_SUPPLIER, headers, JSON.toJSONString(param));
        System.out.println(result);
        if(StringUtils.isNotEmpty(result)){
            result= result.startsWith("\"") && result.endsWith("\"") ? result.substring(1, result.length() - 1) : result;
            return JsonResult.success(result);
        }else{
            return JsonResult.fail("创建失败");
        }

    }

    @Override
    public JsonResult updateSupplier(SupplierCreateRequest supplierCreateRequest) {
        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
        headers.put("openToken", redisHelper.getValue("chanjetToken").toString());

        Map<String, Object> param = new HashMap<>();
        Map<String, Object> deptParamObj = new HashMap<>();

        deptParamObj.put("Code", supplierCreateRequest.getCode());
        deptParamObj.put("Name", supplierCreateRequest.getName());
        deptParamObj.put("ID", supplierCreateRequest.getID());

        param.put("dto", deptParamObj);

        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.UPDATE_SUPPLIER, headers, JSON.toJSONString(param));
        System.out.println(result);
        if(StringUtils.isNotEmpty(result)){
            return JsonResult.success(result);
        }else{
            return JsonResult.fail("修改失败");
        }
    }

    @Override
    public List<SupplierPartnerClassResponse> getSupplierListPartnerClass() throws JsonProcessingException {
        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
        headers.put("openToken", redisHelper.getValue("chanjetToken").toString());

        Map<String, Object> param = new HashMap<>();
        HashMap resultMap= new HashMap<>();
        resultMap.put("SelectFields","id,code,name,ts,parent.name,parent.code,parent.id");
        param.put("param", resultMap);

        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.QUERY_SUPPLIER_PARTNER_CLASS, headers, JSON.toJSONString(param));

        // 将字符串解析为JSONArray
        JSONArray jsonArray = JSON.parseArray(result);
        List<SupplierPartnerClassResponse> dataList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            // 创建SupplierCategory实例
            SupplierPartnerClassResponse supplierCategory = new SupplierPartnerClassResponse();

            // 设置直接属性
            supplierCategory.setCode(jsonObject.getString("code"));
            supplierCategory.setName(jsonObject.getString("name"));
            supplierCategory.setId(jsonObject.getString("id"));
            supplierCategory.setTs(jsonObject.getString("ts"));

            // 创建Parent实例并设置其属性
            SupplierPartnerCodeClassResponse parent = new SupplierPartnerCodeClassResponse();

            parent.setName(jsonObject.getString("parent.name"));
            parent.setCode(jsonObject.getString("parent.code"));
            parent.setId(jsonObject.getString("parent.id"));

            // 设置SupplierCategory的parent属性
            supplierCategory.setParent(parent);
            dataList.add(supplierCategory);
            // 输出结果以验证是否正确解析
          }
         return dataList;
    }

    @Override
    public JsonResult createSupplierPartnerClass(SupplierPartnerClassCreateRequest supplierPartnerClassCreateRequest) {

        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
        headers.put("openToken", redisHelper.getValue("chanjetToken").toString());

        // 创建最外层map，包含dto
        Map<String, Object> root = new HashMap<>();
        root.put("dto", JSON.toJSON(supplierPartnerClassCreateRequest));


        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.CREATE_SUPPLIER_PARTNER_CLASS, headers, JSON.toJSONString(root));
        System.out.println(result);
        if(StringUtils.isNotEmpty(result)){
            String msg=result;
            return JsonResult.success(msg);
        }else{
            return JsonResult.fail("创建失败");
        }
    }


}
